﻿using ApiDemo;
using Castle.DynamicProxy;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TianYuan.Core.Dependency;
using TianYuan.Core.Domain.Uow.Interception;
using TianYuan.Data.Dapper;

namespace TianYuan.Data.Dapper
{
    public class SqlFilterInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget;

            if (method.IsDefined(typeof(SqlFilterAttribute), false))
            {
                IDbContext dbContext = IocManager.Instance.Resolve<IDbContext>();
                var attrs = invocation.MethodInvocationTarget.GetCustomAttributes(typeof(SqlFilterAttribute), false);
                if (attrs.Length > 0)
                {
                    SqlFilterAttribute attr=(SqlFilterAttribute)attrs[0];
                    try
                    {
                        dbContext.QueryFilter
                         .Add(new SqlFilterItem()//单表全局过滤器
                         {
                             FilterName = attr.FilterName,
                             FilterValue = filterDb =>
                             {
                                 return new SqlFilterResult() { Sql = attr.Sql, Parameters = attr.Parameters};
                             },
                             IsJoinQuery = attr.IsJoinQuery
                         });
                        invocation.Proceed();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                else
                {
                    throw new Exception("获取SqlFilter错误！");
                }
            }
            {
                invocation.Proceed();
            }
        }
        
    }
}
